//
//  ZZHomeViewController.swift
//  web
//
//  Created by 张卓 on 2017/1/16.
//  Copyright © 2017年 ZZ. All rights reserved.
//

import UIKit


let homeCellID = "HomeCellID"
class ZZHomeViewController: ZZVisitorViewController {
    
    lazy var homeViewModel:ZZHomeViewModel = ZZHomeViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        if !isLogin {
            visitorView?.setupVisiorViewInfo(imgName: nil, title: nil)
            
            return 
        }
        setupUI()
        loadData()
    }
    
    //设置视图   私有
    private func setupUI() {
        navigationController!.view.insertSubview(pushLabel, belowSubview: navigationController!.navigationBar)
        setupNav()
        setupTableViewInfo()
    }
    //设置导航条
    private func setupNav(){
     
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: "navigationbar_friendsearch", target: self, action: #selector(leftBntClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: "navigationbar_pop", target: self, action: #selector(rightBntClick))
    }
    
    /// 设置tableView相关信息
    private func setupTableViewInfo(){
        //设置数据源方法
        tableView.dataSource = self
        tableView.delegate = self
        //注册机制
        tableView.register(ZZHomeTableViewCell.self, forCellReuseIdentifier: homeCellID)
        //设置行高
//        tableView.rowHeight = 200
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 200
        //隐藏分割线
        tableView.separatorStyle = .none
        //底部视图
        tableView.tableFooterView = footView
        //添加下拉刷新控件
        tableView.addSubview(refreshControl)
        
        //监听点击事件
        refreshControl.addTarget(self, action: #selector(refreshAction), for: UIControlEvents.valueChanged)
    }
    //下拉刷新  懒加载  风火轮
    fileprivate lazy var footView :UIActivityIndicatorView = {
       let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
        //设置颜色
        view.color = ZZThemeColor
        return view
    }()
    
    //系统下拉刷新控件
//    fileprivate lazy var refreshControl : UIRefreshControl = UIRefreshControl()
    fileprivate lazy var refreshControl : ZZRefreshControl = ZZRefreshControl()
    
    // 下拉刷新指示label
    fileprivate lazy var pushLabel :UILabel = {
       let lab = UILabel(fontSize: ZZNORMALFONTSIZE, textColor: UIColor.white)
        lab.frame = CGRect(x: 0, y: 64 - 35, width: ZZSCREENW, height: 35)
        lab.textAlignment = .center
        lab.backgroundColor = ZZThemeColor
        lab.isHidden = true
        return lab
    }()
    
    
}

extension ZZHomeViewController: UITableViewDataSource,UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return homeViewModel.dataArr.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: homeCellID, for: indexPath) as! ZZHomeTableViewCell
        cell.statusViewModel = homeViewModel.dataArr[indexPath.row]
        return cell
    }
    
    //将要显示
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indexPath.row == homeViewModel.dataArr.count - 1 && !footView.isAnimating{
            //开启风火轮模式
            footView.startAnimating()
            //开始请求数据
            loadData()
        }
    }
    
    //取消点击效果
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
    
    
}


//MARK - 获取首页数据
extension ZZHomeViewController{
    
    func loadData(){
        
        homeViewModel.getHomeData(isPullUp: footView.isAnimating) { (isFinsh,count) in
            // 在风火轮没有动画的时候 就代表是下拉刷新 才执行lable的动画
            if !self.footView.isAnimating {
                self.setPushLabelAmin(count: count)
            }
            if !isFinsh {
                print("失败")
            }else{
                //刷新tableView
                self.tableView.reloadData()
            }
         self.endRefreshing()
        }
    }
    // 设置下拉刷新指示label的动画&&给lable设置text  -> 监测为下拉刷新的时候才会执行动画
    func setPushLabelAmin(count:Int){
        // 判断如果你的lable在显示 就说明你在执行动画 我们就不要在执行动画
        if !self.pushLabel.isHidden {
            return
        }
        // label显示的内容
        var text = ""
        // 没有更新到微博
        if count <= 0 {
            text = "您已经是最新的微博啦"
        }else {
            text = "您更新到\(count)条新微博"
        }
        
        // 赋值
        self.pushLabel.text = text
        // 显示lable
        self.pushLabel.isHidden = false
        // 设置pullDownTipLabel 动画
        UIView.animate(withDuration: 0.5, animations: {
            // 叫lable下来
            self.pushLabel.transform = CGAffineTransform(translationX: 0, y: 35)
        }) { (_) in
            // 设置动画恢复原来的位置
            UIView.animate(withDuration: 0.5, delay: 1, options: [], animations: {
                self.pushLabel.transform = CGAffineTransform.identity
            }, completion: { (_) in
                // 隐藏
                self.pushLabel.isHidden = true
            })
        }
    }
    //结束动画方法
    func endRefreshing(){
        //关闭风火轮
        self.footView.stopAnimating()
        //停止系统刷新控件动画
        self.refreshControl.endRefreshing()
    }
}

// 代码分块
// 监听事件
extension ZZHomeViewController {
    
    //按钮点击事件
    @objc fileprivate func leftBntClick() {
        print("点击左上角按钮")
    }
    
    //按钮点击事件
    @objc fileprivate func rightBntClick() {
        print("点击右上角按钮")
        let scanVC = ZZScanViewController()
        navigationController?.pushViewController(scanVC, animated: true)
    }
    //监听首页下拉刷新时间
    @objc fileprivate func refreshAction(){
        //请求数据
        loadData()
    }
    
    
    
    
    
}








